package com.neuedu.common;

import java.sql.*;

public class DBUtil {
    public static ThreadLocal<Connection> tl = new ThreadLocal<>();
    //得到connection
    public static Connection getCon(){
        Connection con = tl.get();
        if (con==null){
            try {
                con=createConnection();
                tl.set(con);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return con;
    }



    //创建Connection
    public static Connection createConnection(){
        Connection con = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            String url = "jdbc:mysql://localhost:3306/his?characterEncoding=UTF-8&serverTimezone=GMT%2B8";
            String name = "root";
            String pwd = "*****";
            con = DriverManager.getConnection(url, name, pwd);

        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
        return con;
    }
    //    关闭资源
    public static void close(ResultSet rs, PreparedStatement ps, Connection conn){

        try {
            if (rs!=null){
                rs.close();
            }
            if (ps!=null){
                ps.close();
            }
            if (conn!=null){
                conn.close();
            }
            tl.remove();
            System.out.println("相关资源已关闭！");
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    public static void close(PreparedStatement ps,Connection conn){

        try {
            if (ps!=null){
                ps.close();
            }
            if (conn!=null){
                conn.close();
            }
            tl.remove();
            System.out.println("相关资源已关闭！");
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
    public static void close(Connection conn){

        try {
            if (conn!=null){
                conn.close();
            }
            tl.remove();
            System.out.println("数据库资源已关闭！");
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}
